<?php

namespace App\Http\Controllers\Admin;


use App\Common\CommonHelpers;
use App\Http\Controllers\BaseController;
use App\Models\RsUsers;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;

class UserController extends BaseController{

    //获取用户列表信息
    public function index(Request $request){
        return view('admin.user.index');
    }

    //获取用户信息
    public function apiList(Request $request){
        //查询消息数据
        $data=RsUsers::listss($request->input('page', 1), $request->input('limit', 20), $request->input());

        return response($data ? array_merge(['code' => 0, 'msg' => '查询成功'],  $data) : ['code' => 906, 'msg' => '当前没有更多数据']);
    }

    //解除绑定
    public function Unbound(Request $request){
        $user_id=$request->post('user_id');
        $data=RsUsers::query()->where('user_id','=',$user_id)->update(['group_id'=>'']);
        return CommonHelpers::responseFormat(0,'','解绑成功');
    }

    public function selectList(Request $request){
        return view('admin.user.selectlist');

    }

    public function apiSelectList(Request $request){
        $data=User::lists($request->input('page', 1), $request->input('limit', 20));
        return response($data ? array_merge(['code' => 0, 'msg' => '查询成功'],  $data) : ['code' => 906, 'msg' => '当前没有更多数据']);

    }
    //添加权限人员
    public function PmsCreate(Request $request){

        $messages = [
            'user_id.required' => '请选择权限人员',

        ];
        $validate = \Validator::make($request->all(), [
            'user_id'=>'required|array',   //消息序号

        ],$messages);
        //判断是否参数完整
        if ($validate->fails()){
            return CommonHelpers::responseFormat(100,'',$validate->errors()->first());
            // return $this->failed($validate->errors()->first());
        }

        $user_ids=$request->input('user_id');  //用户id
        $user_names=$request->input('name'); //用户名
        $username=$request->input('username');  //工号

        foreach ($user_ids as $k=>$val){
            //查询是否已存在用户

            $is_user=RsUsers::query()->where('user_id',$val)->exists();

            if($is_user){
                unset($user_ids[$k]);
                unset($user_names[$k]);
                unset($username[$k]);
            }


        }
        foreach ($user_ids as $k=>$val){
            $data[]=[
                'user_id'=>$val,
                'username'=>$user_names[$k],
                'loginname'=>$username[$k],

                'create_time'=>Carbon::now()
            ];
        }
        $res=RsUsers::insert($data);
        if($res){
            return CommonHelpers::responseFormat(0,'','添加成功');

        }else{
            return CommonHelpers::responseFormat(99,'','添加失败');
        }

    }


}
